<?php
class PackageExclusionController extends CBaseController
{		
	protected $package;
	protected $exclusion;
	protected $validator;
	public function __construct($config=null) 
    { 
      parent::__construct($config);	  
    } 
	
	public function init($tpl)
	{
		parent::init($tpl);
		$this->reqLogin();
		$this->templator->addViewsDir(dirname(__FILE__).'/../views');
		$this->templator->assign('menu','exclusion');
		$this->prepare();
	}
	
	public function prepare()
	{
		if(isset($_GET['id']))
		{
			$id = $_GET['id'];
			$this->package = R::load('travelpackage',$id);
		}
		elseif(isset($_POST['id']))
		{	
			$id = $_POST['id'];
			$this->package = R::load('travelpackage',$id);
		}
		else
		{
			$this->package = R::dispense('travelpackage');
		}
		$this->prepareExclusion();
	}	
	
	public function prepareExclusion()
	{
		if(isset($_GET['exclusion_id']))
		{
			$id = $_GET['exclusion_id'];
			$this->exclusion = R::load('exclusion',$id);
		}
		elseif(isset($_POST['exclusion_id']))
		{	
			$id = $_POST['exclusion_id'];
			$this->exclusion = R::load('exclusion',$id);
		}
		else
		{
			$this->exclusion = R::dispense('exclusion');
		}
	}
	
	public function saveORupdateValidate()
	{
		$this->validator = new FormValidator();
		$this->validator->addValidation("name","req","Please fill in Name");
		return $this->validator->ValidateForm();
	}
	
	public function savePrepare()
	{
		$this->exclusion->name = $_POST['name'];
		$this->exclusion->position = $_POST['position'];
		$this->exclusion->longdesc = $_POST['longdesc'];
	}
		
	
	public function save()
	{
		$this->savePrepare();
		  if($this->saveORupdateValidate())
		  {
			if(isset($this->exclusion->id) && !empty($this->exclusion->id))
				$this->package->ownExclusion[$this->exclusion->id]=$this->exclusion;
			else
				$this->package->ownExclusion[]=$this->exclusion;
			R::store($this->package);
			$this->templator->assign('info','exclusion added sucessfully');
			$this->exclusion = R::dispense('exclusion');
			$this->exclusions();	
		  }
		  else
		  {
			$error_hash = $this->validator->GetErrors();
			$this->templator->assign('validate_errors',$error_hash);
			$this->exclusions();
		  }
			
	}
	
	public function update()
	{
		$this->save();	
	}
	
	public function edit()
	{
		$this->exclusions();	
	}
	
	public function delete()
	{
		R::trash($this->exclusion);
		$this->exclusion = R::dispense('exclusion');
		$this->exclusions();	
	}
	
	public function exclusions()
	{		
		//$assignedExclusion= R::related( $this->package, 'exclusion' );
		$this->templator->assignByRef('package',$this->package);		
		$this->templator->assignByRef('exclusion',$this->exclusion);		
		$this->templator->assign('exclusions',array_merge($this->package->ownExclusion, array()));
		$this->templator->display('exclusion/package_exclusion.html');
	}
	
	
}	